<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { NAlert, NButton, NCard, NModal, NSpace, NSpin, NStep, NSteps, NUpload } from 'naive-ui';
import { InventoryGoods } from '@/service/api/inventory';
import { useAuthStore } from '@/store/modules/auth';
import StockSelector from '@/components/stock/selector.vue';
import type { StockSelectEmitData } from '@/components/stock/types';

// 类型定义
interface ImportResult {
  addNum: number;
  updateNum: number;
  errNum: number;
  errKeys?: number[];
}

interface TemplateOption {
  type: 'common' | 'morePackunits' | 'morePackModel';
  title: string;
  description: string;
}

// 响应式数据
const authStore = useAuthStore();
const active = ref(0);
const loading = ref(false);
const showResultModal = ref(false);
const uploadRef = ref();

// 表单数据
const form = reactive({
  optionType: 'common' as 'common' | 'morePackunits' | 'morePackModel',
  stockId: '',
  file: null as File | null
});

const importResult = ref<ImportResult>({
  addNum: 0,
  updateNum: 0,
  errNum: 0,
  errKeys: []
});

// 模板选项配置
const templateOptions: TemplateOption[] = [
  {
    type: 'common',
    title: '通用模板',
    description: '不包含多规格、多单位适用绝大多数商品'
  },
  {
    type: 'morePackunits',
    title: '多单位模板',
    description: '适合多个单位的商品'
  },
  {
    type: 'morePackModel',
    title: '多规格模板',
    description: '适用于多个规格的商品'
  }
];

// 权限检查
const hasImportPermission = computed(() => {
  const rights = authStore.getInventoryRights();
  return rights?.good?.add || rights?.good?.modify;
});

// 计算属性
const canProceed = computed(() => {
  const debug = {
    active: active.value,
    file: form.file,
    stockId: form.stockId,
    hasPermission: hasImportPermission.value
  };
  console.log('canProceed debug:', debug);

  if (active.value === 0) {
    // 第一步：选择了模板类型
    return form.optionType !== null && form.optionType !== undefined;
  }
  if (active.value === 1) {
    // 第二步：上传了文件并且有权限（不强制要求选择店仓）
    const result = form.file !== null && hasImportPermission.value;
    console.log('Step 1 canProceed result:', result);
    return result;
  }
  return false;
});

// 方法
const handleTemplateSelect = (templateType: 'common' | 'morePackunits' | 'morePackModel') => {
  form.optionType = templateType;
  active.value = 1;
};

const handleDownloadTemplate = (templateType: 'common' | 'morePackunits' | 'morePackModel') => {
  InventoryGoods.downloadTemplate(templateType);
  window.$message?.success('模板下载中...');
};

const handleStockSelect = (data: StockSelectEmitData) => {
  console.log('handleStockSelect called with:', data);
  form.stockId = data.objectId;
  console.log('form.stockId updated to:', form.stockId);
};

const handleFileChange = ({ file, fileList }: any) => {
  // 由于设置了 :default-upload="false"，文件不会自动上传
  // 直接获取选中的文件，不需要检查状态
  if (file && file.file) {
    form.file = file.file;
  } else if (fileList && fileList.length > 0) {
    // 备选方案：从fileList中获取
    const lastFile = fileList[fileList.length - 1];
    if (lastFile && lastFile.file) {
      form.file = lastFile.file;
    }
  } else {
    // 文件被移除时清空
    form.file = null;
  }
};

const handlePrevious = () => {
  active.value = Math.max(0, active.value - 1);
};

const handleNext = () => {
  if (active.value === 0 && form.optionType) {
    active.value = 1;
  }
};

const handleUpload = async () => {
  // 权限检查 - 商品导入需要商品添加权限
  const rights = authStore.getInventoryRights();
  if (!rights?.good?.add && !rights?.good?.modify) {
    window.$message?.error('暂无商品导入权限');
    return;
  }

  if (!form.file) {
    window.$message?.error('请选择要上传的文件');
    return;
  }

  // 店仓参数优化：如果没有选择店仓，传递空字符串（由后端处理默认逻辑）
  // 不再强制要求必须选择店仓

  loading.value = true;

  // 构建FormData
  const formData = new FormData();
  formData.append('file', form.file);
  formData.append('stockId', form.stockId || ''); // 如果没有选择店仓，传递空字符串
  formData.append('optionType', form.optionType);
  formData.append('source', 'PC');

  // 添加权限信息
  const permissions = authStore.getInventoryRights();
  if (permissions) {
    formData.append('canSeeCostprice', String(permissions.good?.canSeeCostprice || false));
    formData.append('selectStocks', JSON.stringify(permissions.stock?.selectStocks || []));
    formData.append('selectCustoms', JSON.stringify(permissions.custom?.selectCustoms || []));
    formData.append('seeMyCustom', String(permissions.custom?.seeMyCustom || false));
    formData.append('seeMyOrder', String(permissions.order?.seeMyOrder || false));
  }

  const response = await InventoryGoods.importGoods(formData);

  // 库存助手API标准响应结构处理
  const actualResponse = (response as any).response?.data;
  
  if (response && actualResponse && actualResponse.code === 1) {
    // 导入成功 - 使用response.data（已经是处理后的数据）
    importResult.value = (response as any).data;
    showResultModal.value = true;

    // 重置表单
    active.value = 0;
    form.file = null;
    form.stockId = '';
    form.optionType = 'common';

    // 清空上传组件
    if (uploadRef.value) {
      uploadRef.value.clear();
    }

    window.$message?.success('商品导入完成！');
  } else {
    window.$message?.error(actualResponse?.msg || '导入失败');
  }

  loading.value = false;
};

const handleReset = () => {
  active.value = 0;
  form.file = null;
  form.stockId = '';
  form.optionType = 'common';
  if (uploadRef.value) {
    uploadRef.value.clear();
  }
};
</script>

<template>
  <div class="h-screen flex flex-col bg-gray-100 p-4">
    <NCard class="flex-1" title="商品导入">
      <!-- 步骤指示器 -->
      <div class="mb-8">
        <NSteps :current="active" size="small">
          <NStep title="选择模板" />
          <NStep title="上传文件" />
        </NSteps>
      </div>

      <!-- 步骤1: 模板选择 -->
      <div v-if="active === 0" class="space-y-6">
        <div class="grid grid-cols-1 gap-6 md:grid-cols-3">
          <NCard
            v-for="template in templateOptions"
            :key="template.type"
            class="cursor-pointer transition-all duration-200 hover:shadow-lg"
            :class="{ 'ring-2 ring-blue-500': form.optionType === template.type }"
            @click="handleTemplateSelect(template.type)"
          >
            <div class="text-center">
              <!-- 图标 -->
              <div class="mb-4">
                <SvgIcon icon="mdi:file-excel" class="mx-auto h-16 w-16 text-green-600" />
              </div>

              <!-- 标题和描述 -->
              <div class="mb-6">
                <h3 class="mb-2 text-16px font-bold">{{ template.title }}</h3>
                <p class="text-13px text-gray-600">{{ template.description }}</p>
              </div>

              <!-- 操作按钮 -->
              <NSpace justify="space-between">
                <NButton type="error" size="small" @click.stop="handleDownloadTemplate(template.type)">
                  点击下载
                </NButton>
                <NButton type="primary" size="small" @click="handleTemplateSelect(template.type)">
                  选择，进行下一步
                </NButton>
              </NSpace>
            </div>
          </NCard>
        </div>

        <NAlert type="warning" show-icon class="mt-6">一次最多上传1000条数据</NAlert>
      </div>

      <!-- 步骤2: 文件上传 -->
      <div v-if="active === 1" class="space-y-6">
        <!-- 文件上传区域 -->
        <div class="flex justify-center">
          <div class="w-full max-w-2xl">
            <NUpload
              ref="uploadRef"
              :multiple="false"
              accept=".xls,.xlsx"
              :max="1"
              :default-upload="false"
              class="w-full"
              @change="handleFileChange"
            >
              <div class="w-full border-2 border-gray-300 rounded-lg border-dashed p-12 transition-colors hover:border-blue-500">
                <SvgIcon icon="mdi:cloud-upload" class="mx-auto mb-4 h-12 w-12 text-gray-400" />
                <p class="text-gray-600">
                  将文件拖到此处，或
                  <span class="cursor-pointer text-blue-500">点击上传</span>
                </p>
                <p class="mt-2 text-12px text-gray-500">只能上传xls,xlsx文件</p>
              </div>
            </NUpload>
          </div>
        </div>

        <!-- 库存选择 -->
        <div class="flex justify-center">
          <div class="w-full max-w-2xl rounded-lg border border-gray-200 bg-white p-6 shadow-sm">
            <!-- 标题和选择器 -->
            <div class="mb-4 flex items-center justify-between">
              <div class="flex items-center">
                <SvgIcon icon="mdi:warehouse" class="mr-2 h-18px w-18px text-blue-500" />
                <label class="text-15px text-gray-800 font-semibold">选择店仓</label>
              </div>
              <div class="flex-1 ml-4">
                <StockSelector
                  v-model="form.stockId"
                  placeholder="请选择店仓（可选）"
                  class="w-full"
                  @selectStock="handleStockSelect"
                />
              </div>
            </div>

            <!-- 提示信息 -->
            <div class="rounded-md border border-orange-200 bg-orange-50 p-3">
              <div class="flex items-start">
                <SvgIcon icon="mdi:information-outline" class="mr-2 mt-0.5 h-16px w-16px text-orange-500 flex-shrink-0" />
                <div class="text-13px text-orange-700 leading-relaxed">
                  <div class="font-medium mb-1">温馨提示</div>
                  <div>不选择店仓时，导入的商品库存数量将默认为 <span class="font-semibold text-orange-800">0</span></div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 权限提示 -->
        <div v-if="!hasImportPermission" class="text-center">
          <NAlert type="error" show-icon class="mx-auto max-w-md">
            暂无商品导入权限，请联系管理员
          </NAlert>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="mt-8 flex justify-center space-x-4">
        <NButton v-if="active > 0" @click="handlePrevious">上一步</NButton>

        <NButton v-if="active === 0" type="primary" :disabled="!canProceed" @click="handleNext">下一步</NButton>

        <NButton v-if="active === 1" type="success" :loading="loading" :disabled="!canProceed" @click="handleUpload">
          开始导入
        </NButton>

        <NButton @click="handleReset">重置</NButton>
      </div>

      <!-- 注意事项 -->
      <div class="mt-8 border border-red-200 rounded-lg bg-red-50 p-4">
        <h4 class="mb-2 text-red-800 font-medium">导入商品资料注意事项</h4>
        <div class="text-13px text-red-700 space-y-1">
          <div>1. 其中"商品名字"，"分类"，"基本单位"这三个为必填</div>
          <div>2. 如表格中"商品编号"与系统内重复则会直接用表格内数据覆盖系统内数据；</div>
          <div>3. 如表格中出现多个"商品编号"重复商品，则会取最后一条数据；</div>
          <div>
            4.
            如表格中的"商品编号"与系统内无重复，则"商品名称"、"规格"两个字段同时确立该商品的唯一性，只要有其中一个字段不同皆可以导入成一个新商品。如果全部重复则会取最后一行数据;
          </div>
          <div>5. 如您未填写"商品编号"系统会为您自动生成一个；</div>
          <div>6. 不同商品间的"商品编号"和"条形码"不能重复；</div>
          <div>7. "分类"一栏支持以如下格式录入多级分类目录：服装/童装。（目前只能支持到二级分类）</div>
          <div>8. 选择"全部店仓"时，填写的库存数量默认为初始数量；如果选择单个店仓，则库存数量为选择店仓的库存数量</div>
        </div>
      </div>
    </NCard>

    <!-- 导入结果弹窗 -->
    <NModal v-model:show="showResultModal" preset="dialog" title="上传成功" :mask-closable="false">
      <div class="space-y-2">
        <div>
          1、新增数据
          <span class="text-green-600 font-medium">{{ importResult.addNum }}</span>
          条
        </div>
        <div>
          2、更新数据
          <span class="text-green-600 font-medium">{{ importResult.updateNum }}</span>
          条
        </div>
        <div>
          3、错误数据
          <span class="text-red-600 font-medium">{{ importResult.errNum }}</span>
          条
        </div>

        <div v-if="importResult.errKeys && importResult.errKeys.length > 0" class="pl-4 space-y-1">
          <div v-for="(errLine, index) in importResult.errKeys" :key="index" class="text-12px text-red-600">
            错误行数{{ errLine }}
          </div>
        </div>
      </div>

      <template #action>
        <NButton type="primary" @click="showResultModal = false">确定</NButton>
      </template>
    </NModal>
  </div>
</template>

<style scoped>
/* 企业级样式，保持项目一致性 */
:deep(.n-card .n-card-header) {
  font-size: 16px;
  font-weight: 600;
}

:deep(.n-steps .n-step .n-step-header .n-step-header-main .n-step-title) {
  font-size: 14px;
}

:deep(.n-upload .n-upload-dragger) {
  border: none;
}

/* 修复上传组件宽度问题 */
:deep(.n-upload) {
  width: 100% !important;
}

:deep(.n-upload .n-upload-trigger) {
  width: 100% !important;
}
</style>
